﻿using EasyNet.Componets.Core.Serialization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyNet.Componets.Core;
using System.IO;

namespace EasyNet.Componets.Json
{
    public class NewtonJson : IJsonSerialization
    {
        
        public NewtonJson()
        {
        }

        public string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public void Serialize(object value, System.Type type, System.IO.Stream writeStream)
        {
            var json = JsonConvert.SerializeObject(value, type, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Error,
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
            });

            writeStream = json.ToStream();
        }

        public T Deserialize<T>(string value)
        {
            return JsonConvert.DeserializeObject<T>(value, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Error
            });
        }

        public object Deserialize(System.Type type, System.IO.Stream stream)
        {
            string value = string.Empty;
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);
            value = reader.ReadToEnd();
            return JsonConvert.DeserializeObject(value, type);
        }

        public object Deserialize(string value, Type type)
        {
            return JsonConvert.DeserializeObject(value, type);
        }

    }
}
